#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QRegularExpression>
#include <QDateTime>
#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonObject>
#include <QValueAxis>
#include <csignal>  // 添加这个头文件
#include <QNetworkInterface>  // 网络接口相关
#include <QHostAddress>       // IP地址处理
#include <QDebug>

// 在 initializeNetwork() 方法中替换硬编码的端口
void MainWindow::initializeNetwork()
{
    // 使用配置的TCP端口
    serverPort = ConfigManager::instance().icstcpPort();
    tcpServer = new QTcpServer(this);

    if (!tcpServer->listen(QHostAddress::Any, serverPort)) {
        LOG_GENERAL("TCP Server failed to start: " + tcpServer->errorString());
    } else {
        connect(tcpServer, &QTcpServer::newConnection, this, &MainWindow::handleNewConnection);
        LOG_GENERAL(QString("TCP Server started on port %1").arg(serverPort));
    }

    // 使用配置的UDP端口
    mcuSocket = new QUdpSocket(this);
    if (!mcuSocket->bind(QHostAddress::Any, ConfigManager::instance().icsMcuUdpPort())) {
        LOG_GENERAL("MCU UDP Socket failed to bind: " + mcuSocket->errorString());
    } else {
        connect(mcuSocket, &QUdpSocket::readyRead, this, &MainWindow::processMCUData);
        LOG_GENERAL(QString("MCU UDP Socket bound to port %1").arg(ConfigManager::instance().icsMcuUdpPort()));
    }

    // 相机UDP监听使用配置的端口
    cameraSocket = new QUdpSocket(this);
    if (!cameraSocket->bind(QHostAddress::Any, ConfigManager::instance().icsCameraUdpPort())) {
        LOG_GENERAL("Camera UDP Socket failed to bind: " + cameraSocket->errorString());
    } else {
        connect(cameraSocket, &QUdpSocket::readyRead, this, &MainWindow::processCameraResponse);
        LOG_GENERAL(QString("Camera UDP Socket bound to port %1").arg(ConfigManager::instance().icsCameraUdpPort()));
    }

    // 更新从板卡IP配置
    for (int i = 0; i < 4; ++i) {
        statusLeds.slave[i].ip = ConfigManager::instance().slaveIp(i);
    }

    // 获取本地IP（排除回环地址）
    foreach (const QHostAddress &address, QNetworkInterface::allAddresses()) {
        if (address.protocol() == QAbstractSocket::IPv4Protocol && !address.isLoopback()) {
            m_localIp = address.toString();
            break;
        }
    }
}

void MainWindow::handleNewConnection()
{
    while (tcpServer->hasPendingConnections()) {
        QTcpSocket *client = tcpServer->nextPendingConnection();

        // 设置连接超时（例如30秒）
        QTimer::singleShot(30000, client, [client]() {
            if (client->state() == QAbstractSocket::ConnectedState) {
                client->disconnectFromHost();
            }
        });

        connect(client, &QTcpSocket::readyRead, this, [this, client]() {
            // 读取数据并处理命令
            QByteArray data = client->readAll();
            parseProtocol(QString(data), client);
        });

        connect(client, &QTcpSocket::disconnected, this, &MainWindow::clientDisconnected);

        qDebug() << "New connection from:"
                 << client->peerAddress().toString()
                 << ":" << client->peerPort();
    }
}

// Link按钮点击处理
void MainWindow::onLinkToCameraClicked() {
    QString cmd1 = QString("link_to_camera:$ip=192.168.0.233$port=11000");
    QString cmd2 = QString("link_to_camera:$ip=192.168.0.233$port=%2").arg(11001);

    sendCommandToMCU(cmd1);
    LOG_CAMERA("Device registration information has been sent: " + cmd1);
    sendCameraCommand(cmd2);
    //querySlaveStatus();
    QString cmd3 = QString("link_to_camera:$ip=192.168.0.233$port=11001");
    sendCommandToSlave(cmd3, "192.168.0.101");
    sendCommandToSlave(cmd3, "192.168.0.102");
    sendCommandToSlave(cmd3, "192.168.0.103");
    sendCommandToSlave(cmd3, "192.168.0.104");
}

//配置保存修改
/*void MainWindow::on_btnSetCameraIp_clicked()
{
    QString newIp = ui->lineEditCameraIp->text();
    ConfigManager::instance().setValue("Network", "CameraIP", newIp);
    cameraIp = newIp;
}*/


void MainWindow::readClientData()
{
    QTcpSocket *client = qobject_cast<QTcpSocket*>(sender());
    if (!client) return;

    while (client->bytesAvailable()) {
        QString command = QString::fromUtf8(client->readAll());
        LOG_GENERAL("Received command: " + command);
        parseProtocol(command, client);
    }
}

void MainWindow::clientDisconnected()
{
    QTcpSocket *client = qobject_cast<QTcpSocket*>(sender());
    if (client) {
        qDebug() << "Client disconnected:"
                 << client->peerAddress().toString()
                 << ":" << client->peerPort();
        client->deleteLater();
    }
}
